<?php

namespace encrypt\classes;

/**
 * AES加密解密类
 * Class AES
 * @package encrypt\classes
 */
class AES implements \encrypt\AES
{
	/**
	 * 加密方式
	 * @var string
	 */
	private $method = 'AES-128-CBC';

	/**
	 * options选项
	 * @var int
	 */
	private $options = 0;

	/**
	 * 加密key
	 * @var string
	 */
	private $password = '';

	/**
	 * 向量
	 * @var string
	 */
	private $iv = '';

	/**
	 * 设置key
	 * @param string $password
	 * @return \encrypt\AES
	 */
	public function password(string $password): \encrypt\AES {
		$this->password = $password;
		return $this;
	}

	/**
	 * 设置加密方式
	 * @param string $method
	 * @return $this
	 */
	public function method(string $method) {
		$this->method = $method;
		return $this;
	}

	/**
	 * 设置options选项
	 * @param string $options
	 * @return $this
	 */
	public function options(string $options) {
		$this->options = $options;
		return $this;
	}

	/**
	 * 加密数据
	 * @param string $data
	 * @return string
	 */
	public function encrypt(string $data): string {
		if (!$this->password) {
			return '';
		}
		$ivlength = openssl_cipher_iv_length($this->method);
		$this->iv = openssl_random_pseudo_bytes($ivlength);
		$encdata  = openssl_encrypt($data, $this->method, $this->password, $this->options, $this->iv);
		return $encdata;
	}

	/**
	 * 解密数据
	 * @param string $data
	 * @param string $iv
	 * @return string
	 */
	public function decrypt(string $data,string $iv): string {
		$decdata = openssl_decrypt($data, $this->method, $this->password, $this->options, $iv);
		return $decdata;
	}

	/**
	 * 解密向量
	 * @return mixed
	 */
	public function iv() {
		return $this->iv;
	}

}
